/**
 *  @author :   JiGuangJie
 *  @date   :   2020/5/22
 *  @time   :   14:14
 *  @Email  :   530904731@qq.com
 */
import * as THREE from 'three';
import { Mesh, PerspectiveCamera, BoxGeometry, Scene, WebGLRenderer } from "three";
import '../styles/index.scss';

export default class DrawCube {

    private readonly _renderer: WebGLRenderer;
    private readonly _container: HTMLElement;
    private readonly _camera: PerspectiveCamera;
    private readonly _scene: Scene;
    private readonly _cube: Mesh;
    private _animating: boolean = false;

    // public constructor(innerWidth: number, innerHeight: number,container:HTMLElement) {
    public constructor() {
        this._container = document.getElementById('container') as HTMLElement;
        const { innerWidth, innerHeight } = window;
        // 创建Three.js 渲染器，并添加至body中
        this._renderer = new THREE.WebGLRenderer({
            antialias: true
        });
        this._renderer.setSize(innerWidth, innerHeight);
        this._container.appendChild(this._renderer.domElement);

        this._renderer.domElement.addEventListener('mouseup', this.onMouseUp.bind(this), false);

        // 创建Three.js场景
        this._scene = new THREE.Scene();
        // 创建相机，并添加到场景中
        this._camera = new THREE.PerspectiveCamera(45, this._container.offsetWidth / this._container.offsetHeight, 1, 4000);
        this._camera.position.set(0, 0, 3);

        // 创建一个平行光光源照射到物体上
        let light = new THREE.DirectionalLight(0xffffff, 1.5);
        light.position.set(0, 0, 1);
        this._scene.add(light);

        // 创建一个接受光照并带有纹理映射的立方体，并添加到场景中
        // 首先，创建一个带纹理映射的立方体
        let mapUrl = '../../images/molumen_small_funny_angry_monster.jpg';
        let map = THREE.ImageUtils.loadTexture(mapUrl);

        // 然后创建一个Phong材质来处理着色，并传递给纹理映射
        let material = new THREE.MeshPhongMaterial({ map: map });

        // 创建一个立方体几何体
        let geometry: BoxGeometry = new THREE.BoxGeometry(1, 1, 1);
        // 将几何体和材质放到一个网格中
        this._cube = new THREE.Mesh(geometry, material);

        // 设置网格在场景中的朝向，否则将不会看到立方体的形状
        this._cube.rotation.x = Math.PI / 5;
        this._cube.rotation.y = Math.PI / 5;

        // 将立方体网格添加到场景中
        this._scene.add(this._cube);

        this.run();
    }

    public run() {
        // 渲染场景
        this._renderer.render(this._scene, this._camera);
        // 在下一帧中旋转立方体
        if (this._animating) {
            this._cube.rotation.y -= 0.01;
        }
        // 在另一帧中回调
        requestAnimationFrame(this.run.bind(this));
    }

    private onMouseUp(evt: MouseEvent) {
        console.log('click');
        evt.preventDefault();
        this._animating = !this._animating;
        console.log(this._animating);
    }
}

new DrawCube();
